<?php

namespace App\Observers;

use App\Jobs\SetReSpaceNum;
use App\Models\Common\Constant;
use App\Models\ParkingLot\ParkAreaLog;
use App\Models\ParkingLot\ParkEnterLog;
use App\Models\ParkingLot\Utils;

class ParkAreaLogObserver
{
    public function created(ParkAreaLog $log)
    {
        if ($log->enter_is_open && $log->area_id) {
            $key = $log->area_id;

            if (ParkEnterLog::CAR_TYPE_MTH === $log->car_type) {
                $key .= Constant::CACHE_KEY_AREA_MTH_CAR_NUM;
            } else {
                $key .= Constant::CACHE_KEY_AREA_TEM_CAR_NUM;
            }

            if (null !== \Cache::get($key)) {
                \Cache::increment($key);
            }

            SetReSpaceNum::dispatch($log->area_id)->onQueue(Constant::QUEUE_MIXED);

        }
    }

    public function updated(ParkAreaLog $log)
    {
        if ($log->enter_is_open && $log->area_id) {
            $key = $log->area_id;

            if (ParkEnterLog::CAR_TYPE_MTH === $log->car_type) {
                $key .= Constant::CACHE_KEY_AREA_MTH_CAR_NUM;
                $keyType = 'month';
            } else {
                $key .= Constant::CACHE_KEY_AREA_TEM_CAR_NUM;
                $keyType = 'temp';
            }

            $changes  = $log->getChanges();
            if (array_key_exists('enter_is_open', $changes)) {

                if (null !== \Cache::get($key)) {
                    \Cache::increment($key);
                }

                SetReSpaceNum::dispatch($log->area_id)->onQueue(Constant::QUEUE_MIXED);
            }
            if (array_key_exists('out_at', $changes) || array_key_exists('out_is_open', $changes)) {
                if ($log->out_at || $log->out_is_open) {
                    if (\Cache::get($key)) {
                        \Cache::decrement($key);
                    }

                    if (Utils::getInitTemCarNum($log->area_id, $keyType)) {
                        Utils::decrementInitTemCarNum($log->area_id, $keyType);
                    }

                    SetReSpaceNum::dispatch($log->area_id)->onQueue(Constant::QUEUE_MIXED);
                }
            }
        }
    }

    public function deleted(ParkAreaLog $log)
    {
        if ($log->enter_is_open && $log->area_id) {
            $key = $log->area_id;

            if (ParkEnterLog::CAR_TYPE_MTH === $log->car_type) {
                $key .= Constant::CACHE_KEY_AREA_MTH_CAR_NUM;
            } else {
                $key .= Constant::CACHE_KEY_AREA_TEM_CAR_NUM;
            }

            if (\Cache::get($key)) {
                \Cache::decrement($key);
            }
        }
    }
}
